package com.wephone.Student.ui;

import java.io.File;
import java.io.FileNotFoundException;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.RequestParams;
import com.wephone.Student.R;
import com.wephone.Student.bean.BaseResponse;
import com.wephone.Student.bean.data.ZhidaoAskData;
import com.wephone.Student.network.HttpClient;
import com.wephone.Student.network.MyResponseHandler;
import com.wephone.Student.util.Constants;
import com.wephone.Student.util.Util;

public class ZhidaoEditTieziActivity extends BaseActivity {
	private EditText questionTitleEdit;
	private EditText contentEdit;
	private TextView chooseTagText;
	private Button countryBtn;
	private File photoSavedFile1 = null;
	private String photoSavedName1 = null;
	private File photoSavedFile2 = null;
	private String photoSavedName2 = null;
	private File photoSavedFile3 = null;
	private String photoSavedName3 = null;
	private ImageView addPicImage1;
	private ImageView addPicImage2;
	private ImageView addPicImage3;
	private boolean hasPhotoUpload = false;
	private TextView maxQuestionText;
	private int picIdx=0;
	private ZhidaoAskData askData;
	
	private MyResponseHandler getHandler(){
		MyResponseHandler handler = new MyResponseHandler(ZhidaoEditTieziActivity.this,BaseResponse.class){
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);
				
				if(getDataSuccess){
					Toast.makeText(getApplicationContext(), "问题修改成功", Toast.LENGTH_LONG).show();
//					AddQuestionResponse questionResponse = (AddQuestionResponse)response;
//					System.out.println("------------"+questionResponse.getData().toString());
					setResult(11);
					finish();
					
				}
			}
		};
		return handler;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode==1){
//			System.out.println("-------picIdx---------"+picIdx);
			if(picIdx==0){
				if(photoSavedFile1!=null && photoSavedFile1.exists()){
					hasPhotoUpload = true;
					Bitmap bitmap = Util.getBitmap(getApplicationContext(),photoSavedFile1.getPath(),200);
					addPicImage1.setImageBitmap(bitmap);
					addPicImage1.setVisibility(View.VISIBLE);
	       		 	Util.saveMyBitmap(bitmap,photoSavedName1,getApplicationContext());
	       		 	picIdx++;
				}else if(data!=null){
					Bundle bundle = data.getExtras();
					if(bundle!=null){
						Bitmap tmpbitmap = (Bitmap)bundle.get("data");
						if(tmpbitmap!=null){
							hasPhotoUpload = true;
							addPicImage1.setImageBitmap(tmpbitmap);
							addPicImage1.setVisibility(View.VISIBLE);
			       		 	Util.saveMyBitmap(tmpbitmap,photoSavedName1,getApplicationContext());
			        		picIdx++;
						}
					}
				}
    		}else if(picIdx==1){
    			if(photoSavedFile2!=null && photoSavedFile2.exists()){
        			hasPhotoUpload = true;
        			Bitmap bitmap = Util.getBitmap(getApplicationContext(),photoSavedFile2.getPath(),200);
        			addPicImage2.setImageBitmap(bitmap);
        			addPicImage2.setVisibility(View.VISIBLE);
           		 	Util.saveMyBitmap(bitmap,photoSavedName2,getApplicationContext());
           		 	picIdx++;
    			}else if(data!=null){
    				Bundle bundle = data.getExtras();
    				if(bundle!=null){
    					Bitmap tmpbitmap = (Bitmap)bundle.get("data");
    					if(tmpbitmap!=null){
    						hasPhotoUpload = true;
    						addPicImage2.setImageBitmap(tmpbitmap);
    						addPicImage2.setVisibility(View.VISIBLE);
		           		 	Util.saveMyBitmap(tmpbitmap,photoSavedName2,getApplicationContext());
    		        		picIdx++;
    					}
    				}
    			}
    		}else if(picIdx==2){
    			if(photoSavedFile3!=null && photoSavedFile3.exists()){
        			hasPhotoUpload = true;
        			Bitmap bitmap = Util.getBitmap(getApplicationContext(),photoSavedFile3.getPath(),200);
        			addPicImage3.setImageBitmap(bitmap);
        			addPicImage3.setVisibility(View.VISIBLE);
           		 	Util.saveMyBitmap(bitmap,photoSavedName3,getApplicationContext());
           		 	picIdx++;
    			}else if(data!=null){
    				Bundle bundle = data.getExtras();
    				if(bundle!=null){
    					Bitmap tmpbitmap = (Bitmap)bundle.get("data");
    					if(tmpbitmap!=null){
    						hasPhotoUpload = true;
    						addPicImage3.setImageBitmap(tmpbitmap);
    						addPicImage3.setVisibility(View.VISIBLE);
		           		 	Util.saveMyBitmap(tmpbitmap,photoSavedName3,getApplicationContext());
    		        		picIdx++;
    					}
    				}
    			}
    		}
   	 	}else if(requestCode==2){
	   	 	if(data!=null){
	   		 	Uri selectedImage = data.getData();
		        String[] filePathColumn = {MediaStore.Images.Media.DATA};
		        Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
		        cursor.moveToFirst();
		        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
		        String picturePath = cursor.getString(columnIndex);
		        cursor.close();
		        if(!TextUtils.isEmpty(picturePath)){
		        	 File userLogoFile = new File(picturePath);  
		        	 if(userLogoFile.exists()){
		        		 hasPhotoUpload = true;
		        		 Bitmap bitmap = Util.getBitmap(getApplicationContext(),picturePath,200);
		        		 if(picIdx==0){
		        			 addPicImage1.setImageBitmap(bitmap);
		        			 addPicImage1.setVisibility(View.VISIBLE);
			        		 Util.saveMyBitmap(bitmap,photoSavedName1,getApplicationContext());
			        		 picIdx++;
		        		 }else if(picIdx==1){
		        			 addPicImage2.setImageBitmap(bitmap);
		        			 addPicImage2.setVisibility(View.VISIBLE);
			        		 Util.saveMyBitmap(bitmap,photoSavedName2,getApplicationContext());
			        		 picIdx++;
		        		 }else if(picIdx==2){
		        			 addPicImage3.setImageBitmap(bitmap);
		        			 addPicImage3.setVisibility(View.VISIBLE);
			        		 Util.saveMyBitmap(bitmap,photoSavedName3,getApplicationContext());
			        		 picIdx++;
		        		 }
		        	 }
		         }
	   	 	}
   	 	}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_zhidao_edit_tiezi);
		
		init();
	}
	
	private void init(){
		questionTitleEdit = (EditText)findViewById(R.id.add_question_title_edit);
		contentEdit = (EditText)findViewById(R.id.add_question_edit);
		chooseTagText = (TextView)findViewById(R.id.choose_tag_text);
		countryBtn = (Button)findViewById(R.id.btn_country);
		addPicImage1 = (ImageView)findViewById(R.id.btn_add_pic_1);
		addPicImage2 = (ImageView)findViewById(R.id.btn_add_pic_2);
		addPicImage3 = (ImageView)findViewById(R.id.btn_add_pic_3);
		maxQuestionText = (TextView)findViewById(R.id.add_question_max_num_text);
		
		findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		contentEdit.addTextChangedListener(new TextWatcher(){
			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				maxQuestionText.setText("你还可以输入"+(1000-contentEdit.getText().toString().length())+"字");
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
			}});
		
		chooseTagText.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				new AlertDialog.Builder(ZhidaoEditTieziActivity.this).setTitle("问题标签")
				.setItems(R.array.zhidao_add_question_array, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						chooseTagText.setText(getResources().getStringArray(R.array.zhidao_add_question_array)[arg1]);
					}
				}).show();
			}
		});
		
		countryBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				new AlertDialog.Builder(ZhidaoEditTieziActivity.this).setTitle("提问国家")
				.setItems(R.array.zhidao_ask_country_array, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						countryBtn.setText(getResources().getStringArray(R.array.zhidao_ask_country_array)[arg1]);
					}
				}).show();
			}
		});
		
		findViewById(R.id.btn_top_right).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if(questionTitleEdit.getText().toString().length()<=0){
					Toast.makeText(getApplicationContext(), "问题标题必须填写", Toast.LENGTH_LONG).show();
					return;
				}else if(contentEdit.getText().toString().length()<=0){
					Toast.makeText(getApplicationContext(), "问题补充必须填写", Toast.LENGTH_LONG).show();
					return;
				}else if(countryBtn.getText().toString().length()<=0 || countryBtn.getText().toString().equals("提问国家")){
					Toast.makeText(getApplicationContext(), "提问国家必须选择", Toast.LENGTH_LONG).show();
					return;
				}else if(chooseTagText.getText().toString().length()<=0 || chooseTagText.getText().toString().equals("问题标签")){
					Toast.makeText(getApplicationContext(), "问题标签必须选择", Toast.LENGTH_LONG).show();
					return;
				}
				RequestParams params = new RequestParams();
				params.put("id", askData.getId());
				params.put("uid", BaseActivity.getMyInfo(getApplicationContext()).getuId());
				params.put("title", questionTitleEdit.getText().toString());
				params.put("content", contentEdit.getText().toString());
				params.put("country", countryBtn.getText().toString());
//				params.put("school", "");
				params.put("tags", chooseTagText.getText().toString());
				if(hasPhotoUpload && photoSavedFile1!=null && photoSavedFile1.exists()){
					try {
						params.put("askimg1", photoSavedFile1);
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					}
				}
				if(hasPhotoUpload && photoSavedFile2!=null && photoSavedFile2.exists()){
					try {
						params.put("askimg2", photoSavedFile2);
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					}
				}
				if(hasPhotoUpload && photoSavedFile3!=null && photoSavedFile3.exists()){
					try {
						params.put("askimg3", photoSavedFile3);
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					}
				}
				HttpClient.getInstance().post(Constants.API_ZHIDAO_REPIRE_ASK_URL, params, getHandler());
				
				Toast.makeText(getApplicationContext(), "正在提交", Toast.LENGTH_SHORT).show();
			}
		});
		
		findViewById(R.id.add_question_image_text).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if(picIdx>2){
					return;
				}
				new AlertDialog.Builder(ZhidaoEditTieziActivity.this).setTitle("选择头像")
				.setItems(new String[]{"拍照","相册"}, new DialogInterface.OnClickListener(){
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						if(arg1==0){
							File rootFile = new File(Constants.IMAGE_PHOTO_TMP_PATH);
							if(!rootFile.exists()){
								rootFile.mkdirs();
							}
							Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
							if(picIdx==0){
								photoSavedName1 = "addQuesPic_1_"+System.currentTimeMillis()+".jpg";
								photoSavedFile1 = new File(Constants.IMAGE_PHOTO_TMP_PATH+photoSavedName1);
								intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoSavedFile1));
							}else if(picIdx==1){
								photoSavedName2 = "addQuesPic_2_"+System.currentTimeMillis()+".jpg";
								photoSavedFile2 = new File(Constants.IMAGE_PHOTO_TMP_PATH+photoSavedName2);
								intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoSavedFile2));
							}else if(picIdx==2){
								photoSavedName3 = "addQuesPic_3_"+System.currentTimeMillis()+".jpg";
								photoSavedFile3 = new File(Constants.IMAGE_PHOTO_TMP_PATH+photoSavedName3);
								intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoSavedFile3));
							}
		                    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
		                    startActivityForResult(intent, 1);
						}else{
							Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
							startActivityForResult(i, 2);
						}
					}})
				.setNegativeButton("取消", null).show();
			}
		});
		
		Bundle bundle = getIntent().getExtras();
		if(bundle!=null){
			askData = (ZhidaoAskData)bundle.getSerializable("askData");
			questionTitleEdit.setText(askData.getTitle());
			contentEdit.setText(askData.getContent());
			countryBtn.setText(askData.getCountry());
			chooseTagText.setText(askData.getTag());
			picIdx = askData.getPictures().length;
		}
	}

}
